<template>
  <el-card class="attr">
    <!-- inline: 行内表单 -->
    <el-form inline :disabled="disabled">
      <el-form-item label="一级分类">
        <el-select
          placeholder="请选择一级分类"
          v-model="categoryStore.category1Id"
        >
          <!-- 
            label option显示的文字
            value option选中得到的值
           -->
          <el-option
            v-for="c1 in categoryStore.category1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择二级分类"
          v-model="categoryStore.category2Id"
        >
          <el-option
            v-for="c2 in categoryStore.category2List"
            :key="c2.id"
            :label="c2.name"
            :value="c2.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="三级分类">
        <el-select
          placeholder="请选择三级分类"
          v-model="categoryStore.category3Id"
        >
          <el-option
            v-for="c3 in categoryStore.category3List"
            :key="c3.id"
            :label="c3.name"
            :value="c3.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelector",
};
</script>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, watch } from "vue";
import { useCategoryStore } from "@/stores/category";
/*
  1. 一上来请求一级分类数据进行展示
  2. 选择一级分类，请求二级分类展示
  3. 选择二级分类，请求三级分类展示

  问题：
    当重新选择一级分类，二级分类选中的值和数据都要清空，三级分类选中的值和数据都要清空
    当重新选择二级分类，三级分类选中的值和数据都要清空
*/

defineProps<{
  disabled: boolean;
}>();

const categoryStore = useCategoryStore();

// 卸载时，清空数据
onBeforeUnmount(() => {
  categoryStore.$patch({
    category1Id: undefined,
    category2Id: undefined,
    category3Id: undefined,
    category1List: [],
    category2List: [],
    category3List: [],
  });
});

onMounted(async () => {
  // 1. 一上来请求一级分类数据进行展示
  categoryStore.getCategory1List();
});

// 监视一级分类id
// 当一级分类id发送变化，请求二级分类展示
watch(
  () => categoryStore.category1Id,
  async (newVal) => {
    categoryStore.getCategory2List(newVal as number);
  }
);

// 监视二级分类id
// 当二级分类id发送变化，请求三级分类展示
watch(
  () => categoryStore.category2Id,
  async (newVal) => {
    if (!newVal) return;
    categoryStore.getCategory3List(newVal as number);
  }
);
</script>

<style scoped>
/* 深度选择器 */
.attr :deep(.el-form-item) {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
